package services

import (
	"backend/log"
	"backend/models"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

type MenuService struct {
	db *gorm.DB
}

func NewMenuService(db *gorm.DB) *MenuService {
	return &MenuService{db: db}
}

func (s *MenuService) Create(menu *models.Menu) error {
	return s.db.Create(menu).Error
}

func (s *MenuService) Update(menu *models.Menu) error {
	return s.db.Save(menu).Error
}

func (s *MenuService) Delete(id uint) error {
	err := s.db.Where("id = ?", id).Delete(&models.Menu{}).Error
	if err != nil {
		return err
	}
	return nil
}

func (s *MenuService) GetMenu(uuid string) (*models.Menu, error) {

	var menu models.Menu
	err := s.db.Where("id = ?", uuid).First(&menu).Error
	if err != nil {
		return nil, err
	}
	return &menu, nil
}

func (s *MenuService) GetMenuList(q *models.PageInfo, menu *models.Menu) ([]*models.Menu, int64, error) {

	var menus []*models.Menu
	var total int64

	query := s.db.Model(&models.Menu{}).Preload("Parent")
	if menu.Name != "" {
		query = query.Where("name = ?", menu.Name)
	}
	if menu.Path != "" {
		query = query.Where("path = ?", menu.Path)
	}
	if menu.Level != 0 {
		query = query.Where("level = ?", menu.Level)
	}

	// 获取符合条件的总数
	if err := query.Count(&total).Error; err != nil {
		log.Logger.Error("获取菜单总数失败", zap.Error(err))
		return nil, 0, err
	}

	result := query.Order("created_at DESC").Limit(q.Size).Offset((q.Page - 1) * q.Size).Find(&menus)
	if result.Error != nil {
		log.Logger.Error("获取菜单失败", zap.Error(result.Error))
		return nil, 0, result.Error
	}

	return menus, total, nil
}

func (s *MenuService) GetMenuPermission() ([]*models.Menu, error) {
	permission := []*models.Menu{}
	if err := s.db.Find(&permission).Error; err != nil {
		return nil, err
	}
	return permission, nil
}

type PermissionResp struct {
	Id   uint   `json:"id"`
	Name string `json:"name"`
}
